package com.wishwingz.klipper;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.wishwingz.klipper.cache.Cache;
import com.wishwingz.klipper.cache.CacheType;

public class UploadActivity extends SherlockActivity implements OnItemSelectedListener {

	private static final String TEMP_PHOTO_FILE = "temp.PNG";
	private static final int REQ_CODE_PICK_IMAGE = 0;

	private EditText et;
	private ScrollView sv;
	private ImageView iv;

	private Cache cacheBrand;
	private Cache cacheType;
	private Cache cacheModel;

	private Cache cacheModelDynamic;

	private Cache cacheOrigin;
	private Cache cacheExtra;

	private ProgressDialog mLoagindDialog;
	
	//가격 업로드 백그라운드 Task를 위한 핸들러
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 100) {
				mLoagindDialog.dismiss();
				Toast.makeText(UploadActivity.this, "가격이 등록되었습니다", Toast.LENGTH_LONG).show();
				finish();
			} else if (msg.what == -100) {
				mLoagindDialog.dismiss();
				Toast.makeText(UploadActivity.this, "가격 등록에 실패했습니다", Toast.LENGTH_LONG).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_upload);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		// 액티비티 실행 시 자동 EditView 포커싱을 해제하기 위한 설정
		sv = (ScrollView)findViewById(R.id.scrollView);
		et = (EditText)findViewById(R.id.editText4);
		et.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				sv.requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});

		// 캐쉬초기화
		this.cacheBrand = new Cache(this, CacheType.PRODUCT_BRAND);
		this.cacheType = new Cache(this, CacheType.PRODUCT_TYPE);
		this.cacheModel = new Cache(this, CacheType.PRODUCT_MODEL);

		// 브랜드 스피너 로드
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cacheBrand.valueList);

		Spinner sp = (Spinner)this.findViewById(R.id.brand_sp);
		sp.setPrompt("브랜드");
		sp.setAdapter(adapter);
		sp.setOnItemSelectedListener(this);

		// 정품여부, 구성 스피너 로드 - 변동 사항이 적어 하드 코딩
		this.cacheOrigin = new Cache(this, CacheType.PRODUCT_ORIGIN);

		List<String> keyList = new ArrayList<String>();
		keyList.add("1");
		keyList.add("2");

		List<String> valueList = new ArrayList<String>();
		valueList.add("정품");
		valueList.add("병행");

		cacheOrigin.keyList = keyList;
		cacheOrigin.valueList = valueList;

		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cacheOrigin.valueList);

		sp = (Spinner)this.findViewById(R.id.origin_sp);
		sp.setPrompt("정품여부");
		sp.setAdapter(adapter);
		sp.setOnItemSelectedListener(this);

		this.cacheExtra = new Cache(this, CacheType.PRODUCT_EXTRA);

		keyList = new ArrayList<String>();
		keyList.add("1");
		keyList.add("2");

		valueList = new ArrayList<String>();
		valueList.add("본체");
		valueList.add("본체, 렌즈킷");

		this.cacheExtra.keyList = keyList;
		this.cacheExtra.valueList = valueList;

		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cacheExtra.valueList);

		sp = (Spinner)this.findViewById(R.id.extra_sp);
		sp.setPrompt("구성");
		sp.setAdapter(adapter);
		sp.setOnItemSelectedListener(this);
	}

	//홈 버튼 클릭 시 이벤트 처리
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case android.R.id.home:
				finish();
		}
		return super.onOptionsItemSelected(item);

	}

	//갤러리 이미지 가져오기 + 사진 자르기
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageData) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, imageData);
		switch (requestCode) {
			case REQ_CODE_PICK_IMAGE:
				if (resultCode == RESULT_OK) {
					if (imageData != null) {
						String filePath = Environment.getExternalStorageDirectory() + "/" + TEMP_PHOTO_FILE;
						Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
						iv = (ImageView)findViewById(R.id.screen_shot);
						iv.setImageBitmap(selectedImage);
					}
				}
				break;
		}
	}

	/**
	 * 임시 파일 위치를 URI 형태로 리턴
	 * @return
	 */
	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	/**
	 *  SD카드 유무 확인 후 임시 파일 위치 리턴
	 * @return
	 */
	private File getTempFile() {
		if (isSDCARDMOUNTED()) {
			File f = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE);
			try {
				f.createNewFile();
			} catch (IOException e) {

			}
			return f;
		} else {
			return null;
		}
	}
	
	/**
	 * SD카드 유무 확인
	 * @return
	 */
	private boolean isSDCARDMOUNTED() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		return false;
	}

	/**
	 * 버튼 리스너
	 * @param v
	 */
	public void mOnClick(View v) {
		switch (v.getId()) {
			case R.id.cancel_btn:
				finish();
				break;
			case R.id.submit_btn:
				this.doBackGroundSubmit();
				break;
			case R.id.galleryButton:
				Intent i = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				i.setType("image/*");
				i.putExtra("crop", "true");
				i.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
				i.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
				startActivityForResult(i, REQ_CODE_PICK_IMAGE);
				break;
		}
	}

	/**
	 * 가격 등록을 위한 백그라운드 Task
	 */
	private void doBackGroundSubmit() {
		mLoagindDialog = ProgressDialog.show(this, null, "등록 중입니다.", true, false);
		
		Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background");
		thread.start();
	}

	private Runnable doBackgroundThreadProcessing = new Runnable() {
		@Override
		public void run() {
			backgroundThreadProcessing();
		}
	};

	private void backgroundThreadProcessing() {
			//Post 요청에 필요한 파라미터를 맵형태로 세팅
			Map<String, String> parameter = this.makeParameter();
			
			DefaultHttpClient httpClient = null;
    		
    		try{
    			httpClient = new DefaultHttpClient();
    			HttpPost upLoadPost = new HttpPost(
    					"http://1.234.7.150:5007/upload");
    			upLoadPost.setHeader("Connection","Keep-Alive");
    			upLoadPost.setHeader("Accept-Charset", "UTF-8");
    			upLoadPost.setHeader("enctype", "multipart/form-data");
    			
    			MultipartEntity multiEntity = new MultipartEntity(
    					           HttpMultipartMode.BROWSER_COMPATIBLE, null,null);
    			File uploadFile = new File(
    					Environment.getExternalStorageDirectory().getAbsoluteFile(), TEMP_PHOTO_FILE);
    			FileBody fileBody = new FileBody(uploadFile);
    			
    			Charset chars = Charset.forName("UTF-8");
    			StringBody prd_brand_id = new StringBody((String)parameter.get("prd_brand_id"),chars);
    			StringBody prd_category_id = new StringBody((String)parameter.get("prd_category_id"),chars);
    			StringBody prd_model_id = new StringBody((String)parameter.get("prd_model_id"),chars);
    			StringBody prd_opt_a = new StringBody((String)parameter.get("prd_opt_a"),chars);
    			StringBody prd_opt_b = new StringBody((String)parameter.get("prd_opt_b"),chars);
    			StringBody prd_dc_rate = new StringBody((String)parameter.get("prd_dc_rate"),chars);
    			StringBody card_dc = new StringBody((String)parameter.get("card_dc"),chars);
    			StringBody prc_price = new StringBody((String)parameter.get("prc_price"),chars);
    			StringBody prc_url = new StringBody((String)parameter.get("prc_url"),chars);
    			StringBody prc_desc = new StringBody((String)parameter.get("prc_desc"),chars);
    			StringBody prc_shop = new StringBody((String)parameter.get("prc_shop"),chars);
    			StringBody user_idx = new StringBody((String)parameter.get("user_idx"),chars);
   			
    			multiEntity.addPart("prd_brand_id", prd_brand_id);
    			multiEntity.addPart("prd_category_id", prd_category_id);
    			multiEntity.addPart("prd_model_id", prd_model_id);
    			multiEntity.addPart("prd_opt_a", prd_opt_a);
    			multiEntity.addPart("prd_opt_b", prd_opt_b);
    			multiEntity.addPart("prd_dc_rate", prd_dc_rate);
    			multiEntity.addPart("card_dc", card_dc);
    			multiEntity.addPart("prc_price", prc_price);
    			multiEntity.addPart("prc_url", prc_url);
    			multiEntity.addPart("prc_desc", prc_desc);
    			multiEntity.addPart("prc_shop", prc_shop);
    			multiEntity.addPart("user_idx", user_idx);
    			multiEntity.addPart("file", fileBody);
    			    			
    			multiEntity.addPart("fileSize", new StringBody(String.valueOf(uploadFile.length())));
    			
    			upLoadPost.setEntity(multiEntity);
    			
    			HttpResponse httpResponse = httpClient.execute(upLoadPost);
			
    		    int responseCode = httpResponse.getStatusLine().getStatusCode();
    			
    			//정상적인 응답 이라면
    			if( responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_ACCEPTED  ){
    				handler.sendEmptyMessage(100);    				    				
    			}		
    		}catch(Exception e){
    			Log.e("UPLOAD", "문제 발생!", e);
    			handler.sendEmptyMessage(-100);
    		}finally{
    			httpClient.getConnectionManager().shutdown();
    		}
	}
/**
 * 가격 업로드 정보 추출 후 MAP 객체에 세팅
 * @return
 */
	private Map<String, String> makeParameter() {
		//카드 정보 생성 시 사용하는 구분자
		final String COLUMN_ARRAY_SEPERAOR = ",";

		Map<String, String> parameterMap = new HashMap<String, String>();

		Spinner spinner = (Spinner)this.findViewById(R.id.brand_sp);
		parameterMap.put("prd_brand_id", this.cacheBrand.keyList.get(spinner.getSelectedItemPosition()));

		spinner = (Spinner)this.findViewById(R.id.category_sp);
		parameterMap.put("prd_category_id", this.cacheType.keyList.get(spinner.getSelectedItemPosition()));

		spinner = (Spinner)this.findViewById(R.id.model_sp);
		String modelKey = this.cacheModelDynamic.keyList.get(spinner.getSelectedItemPosition());
		parameterMap.put("prd_model_id", modelKey.substring(modelKey.lastIndexOf("_")+1));

		spinner = (Spinner)this.findViewById(R.id.origin_sp);
		parameterMap.put("prd_opt_a", this.cacheOrigin.keyList.get(spinner.getSelectedItemPosition()));

		spinner = (Spinner)this.findViewById(R.id.extra_sp);
		parameterMap.put("prd_opt_b", this.cacheExtra.keyList.get(spinner.getSelectedItemPosition()));

		EditText et = (EditText)this.findViewById(R.id.editText1);
		parameterMap.put("prd_dc_rate", et.getText().toString());

		StringBuilder discountCards = new StringBuilder();

		CheckBox checkBox = (CheckBox)this.findViewById(R.id.checkBox1);
		if (checkBox.isChecked()) {
			discountCards.append("신한").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox2);
		if (checkBox.isChecked()) {
			discountCards.append("국민").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox3);
		if (checkBox.isChecked()) {
			discountCards.append("현대").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox4);
		if (checkBox.isChecked()) {
			discountCards.append("우리").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox5);
		if (checkBox.isChecked()) {
			discountCards.append("롯데").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox6);
		if (checkBox.isChecked()) {
			discountCards.append("외환").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox7);
		if (checkBox.isChecked()) {
			discountCards.append("씨티").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox8);
		if (checkBox.isChecked()) {
			discountCards.append("비씨").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox9);
		if (checkBox.isChecked()) {
			discountCards.append("하나SK").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox10);
		if (checkBox.isChecked()) {
			discountCards.append("삼성").append(COLUMN_ARRAY_SEPERAOR);
		}
		checkBox = (CheckBox)this.findViewById(R.id.checkBox11);
		if (checkBox.isChecked()) {
			discountCards.append("농협").append(COLUMN_ARRAY_SEPERAOR);
		}

		parameterMap.put("card_dc", discountCards.toString());

		et = (EditText)this.findViewById(R.id.editText2);
		parameterMap.put("prc_price", et.getText().toString());

		et = (EditText)this.findViewById(R.id.editText3);
		parameterMap.put("prc_url", et.getText().toString());

		et = (EditText)this.findViewById(R.id.editText4);
		parameterMap.put("prc_desc", et.getText().toString());
		
		//임시 사용자ID, 쇼핑몰 정보
		parameterMap.put("prc_shop", "1");
		parameterMap.put("user_idx", "1");

		return parameterMap;
	}
	
/**
 * 스피너 설정 - 브랜드, 카테고리 스피너 선택에 따라 모델 스피너의 아이템 변경 
 * 
 */
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		Spinner spinner = (Spinner)parent;

		if (spinner.getId() == R.id.brand_sp) {
			//브랜드 스피너 선택 시
			// clear other spinner
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, this.cacheType.valueList);

			Spinner sp = (Spinner)this.findViewById(R.id.category_sp);
			sp.setPrompt("종류");
			sp.setAdapter(adapter);
			sp.setOnItemSelectedListener(this);
			
			
			ArrayList<String> emptyList = new ArrayList<String>();
			emptyList.add("없음");
			
			adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, emptyList);

			sp = (Spinner)this.findViewById(R.id.model_sp);
			sp.setPrompt("모델명");
			sp.setAdapter(adapter);
			sp.setOnItemSelectedListener(this);
			
		} else if (spinner.getId() == R.id.category_sp) {
			//카테고리 스피너 선택 시
			Spinner sp = (Spinner)this.findViewById(R.id.brand_sp);
			String barndKey = cacheBrand.keyList.get(sp.getSelectedItemPosition());
			String typeKey = cacheType.keyList.get(position);
			String modelKeyPreFix = barndKey + "_" + typeKey + "_";

			List<String> keyList = new ArrayList<String>();
			List<String> valueList = new ArrayList<String>();

			for (int i = 0; i < cacheModel.keyList.size(); i++) {
				if (cacheModel.keyList.get(i).startsWith(modelKeyPreFix)) {
					keyList.add(cacheModel.keyList.get(i));
					valueList.add(cacheModel.valueList.get(i));
				}
			}

			if (this.cacheModelDynamic == null) {
				this.cacheModelDynamic = new Cache(this, CacheType.PRODUCT_MODEL);
			}
			this.cacheModelDynamic.keyList = keyList;
			this.cacheModelDynamic.valueList = valueList;

			// set model spinner
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, this.cacheModelDynamic.valueList);

			sp = (Spinner)this.findViewById(R.id.model_sp);
			sp.setPrompt("모델명");
			sp.setAdapter(adapter);
			sp.setOnItemSelectedListener(this);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// Do Nothing
	}
}